//
//  DataSwiftUIView.swift
//  ptbuy
//
//  Created by MyMac on 2024/11/11.
//

import SwiftUI
import CoreData
/**
 对coredata数据库增删查改操作
 */
struct DataSwiftUIView: View {
    @Environment(\.managedObjectContext) private var viewContext
    
    @FetchRequest var people:FetchedResults<Person>
    
    init(){
        _people =  FetchRequest<Person>(
            sortDescriptors: [NSSortDescriptor(
                keyPath: \Person.name,
                ascending: true
            )],
            predicate: nil // 初始时没有任何筛选条件
        )
    }
    
    @State private var name: String = ""
    @State private var age: Int16 = 0
    @State private var searchText: String = ""
    
    var body: some View {
        NavigationView {
            VStack {
                // 搜索框
                TextField("Search by name", text: $searchText)
                    .padding()
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .onChange(of: searchText) { newValue in
                        updateFetchRequest(with: newValue)
                    }
                
                // 输入框
                TextField("Name", text: $name)
                    .padding()
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                
                TextField("Age", value: $age, formatter: NumberFormatter())
                    .padding()
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                
                HStack {
                    // 增加数据
                    Button("Add Person") {
                        addPerson()
                    }
                    .padding()
                    
                    // 清除所有数据
                    Button("Delete All") {
                        deleteAll()
                    }
                    
                    .padding()
                }
                
                List {
                    ForEach(people) { person in
                        VStack(alignment: .leading) {
                            Text(person.name ?? "Unknown")
                                .font(.headline)
                            Text("Age: \(person.age)")
                        }
                    }
                    .onDelete(perform: deletePerson)
                }
                .navigationBarTitle("People List")
                .navigationBarItems(trailing: EditButton())
            }
            .padding()
        }
    }
    
    // 更新 fetchRequest 以实现模糊查询
    private func updateFetchRequest(with searchTerm: String) {
        let predicate: NSPredicate
        if searchTerm.isEmpty {
            predicate = NSPredicate(value: true)  // 如果搜索框为空，则返回所有记录
        } else {
            predicate = NSPredicate(
                /*
                 %@：用于对象（如字符串、数组、日期等）。
                 %d：用于整数。
                 %f：用于浮动类型的数值。
                 %ld：用于长整型（）数值。Long
                 %u：用于无符号整数。
                 */
                format: "name CONTAINS[c] %@",
                searchTerm
            )  // 模糊查询
        }
            
        people.nsPredicate = predicate
        
    }
    
    // 增加一条数据
    private func addPerson() {
        let newPerson = Person(context: viewContext)
        newPerson.name = name
        newPerson.age = age
          
        do {
            try viewContext.save()
        } catch {
            // 处理错误
            print("Error saving context: \(error.localizedDescription)")
        }
    }

    // 删除选中的数据
    private func deletePerson(offsets: IndexSet) {
        //          withAnimation {
        //              offsets.map { people[\$0] }.forEach(viewContext.delete)
        //
        //              do {
        //                  try viewContext.save()
        //              } catch {
        //                  // 处理错误
        //                  print("Error deleting object: \(error.localizedDescription)")
        //              }
        //          }
    }

    // 删除所有数据
    private func deleteAll() {
        let fetchRequest: NSFetchRequest<NSFetchRequestResult> = Person.fetchRequest()
        let batchDeleteRequest = NSBatchDeleteRequest(
            fetchRequest: fetchRequest
        )
          
        do {
            try viewContext.execute(batchDeleteRequest)
        } catch {
            print("Error deleting all: \(error.localizedDescription)")
        }
    }
}

#Preview {
    DataSwiftUIView()
}
